import os

from django.conf import settings
from django.forms import ModelForm

from utils.to_docx import DictToDocx, LogDictDocx
from .models import Resume


class ResumeForm(ModelForm):

    class Meta:
        model = Resume

        fields = ["username", "city", "phone",
        "email", "apply_position", "born_address", "gender", "picture", "attachment",
        "bachelor_school", "master_school", "major", "degree", 
        "candidate_introduction", "work_experience", "project_experience"]

    def save(self, commit=True):

        instance = super().save(commit)
        username = self.cleaned_data.get('username')
        # prefix = instance.prefix if instance.prefix else '.docx'
        # path = DictToDocx(instance.merge_dict()).to_docx(instance.pk, prefix, username)
        # instance.path = path
        # instance.prefix = prefix
        # instance.save()
        username = username if username else ''
        # prefix = resume.prefix if resume.prefix else '.docx'

        logo = LogDictDocx()
        basic_info = instance.basic_info_to_dict()
        logo.add_info_table(basic_info, username=username)
        if instance.candidate_introduction:
            logo.add_introduce(instance.candidate_introduction)

        if instance.get_companies():
            logo.add_work_expirience(instance.get_companies())

        if instance.get_expirience():
            logo.add_project(instance.get_expirience())
        raw_path = os.path.join(settings.BASE_DIR, 'media/resume_upload/raw', f'{instance.pk}-{username}个人简历(原简历).docx')
        parse_path = os.path.join(settings.BASE_DIR, 'media/resume_upload/', f'{instance.pk}-{username}个人简历.docx')
        logo.save(parse_path)

        # path = DictToDocx(resume.merge_dict()).to_docx(resume.pk, prefix, username)
        # resume.path = path
        # resume.save()
        file = open(parse_path, 'rb')
        content = file.read()
        with open(raw_path, 'wb') as f:
            f.write(content)
        instance.parse_content = content
        instance.raw_content = content
        instance.raw_path = raw_path
        instance.parse_path = parse_path
        instance.raw_prefix = '.docx'
        instance.save()
        return instance
